home *** CD-ROM | disk | FTP | other *** search
- Path: itss11.lisd.env.gov.ab.ca!orr
- From: orr@lisd.env.gov.ab.ca (Ron Orr)
- Newsgroups: comp.lang.c++
- Subject: Re: Output to file vs. cout
- Date: 19 Mar 1996 17:05:21 GMT
- Organization: Alberta Environmental Protection
- Message-ID: <4impgh$jnl@is-news.gov.ab.ca>
- References: <JL.96Mar7165152@thyme.id.dth.dk> <4i18mg$ba5@hpbblb.bbn.hp.com>
- NNTP-Posting-Host: itss11.lisd.env.gov.ab.ca
-
- Matthias Dittrich (matti) wrote:
- : jl@id.dth.dk (J°rn Lind-Nielsen) wrote:
- : >
- : >Here's another of the probs that comes from porting C to C++:
- : >
- : >- I want to be able to redirect program output to either a file or cout.
- : > Typically this would be selected by a commandline option ("-o outfile").
- : >
- : >- In C I would do something like this:
- : >
- : >
- : > main()
- : > {
- : > FILE *outputfile;
- : >
- : > if (commandline == do_output_to_file)
- : > outputfile = stdout;
- : > else
- : > outputfile = fopen(passed_filename, "w");
- : >
- : > fprintf(outfile, "Hello world\n");
- : >
- : > fclose(outfile); /* Maybe - not allways necassary */
- : > }
- : >
- : >- The question is: How is this done in C++ ?
- : >
- : >.......
- : ofstream outfile(passed_filename); /* this constructor opens your file */
- : outfile << "Hello world" << endl; /* writes the string */
-
- : The destructor closes the file and of course you should do some error checking.
-
- : Good luck,
- : Matthias
-
- I have the same problem. This solution will force the output only to
- a file.
-
- Is there a way to write an output function to do all your output based
- on what stream you pass it? ie: one mainline step would be to open a file,
- pass the file stream to the function, then close the file. Another mainline
- step would be to pass "cout" to the function.
-
- void OutPut(ofstream &xxx)
- {
- xxx << "this is only written once" << endl;
- }
-
- I tried, but only the file works since it is an oftream object. "cout" is
- an ostream object.
-
- Accourding to the g++ FAQ, the iostream classes do not allow assigning to
- arbitrary streams, therefore "cout" will fail if passed to this function.
-
- So, what is the best way to eliminate duplicate code when you want to
- output to a file and/or standard output? I appologize if I have not hunted
- through enough FAQS thoroughly and the answer is staring at me.
-
- Thanks. Ron
-
-